package com.xuanyuan.pullup

import android.app.ActivityManager
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.widget.Toast
import com.xuanyuan.pullup.PullUpUtils.getAppOpenIntentByPackageName


/**
 * @author 罗发新
 * 创建时间：2021/4/6  14:14
 * 邮件：424533553@qq.com
 * CSDN：https://blog.csdn.net/luo_boke
 * 更新时间：2021/4/6  14:14
 * 文件说明：apk工具文件
 */
object ApkUtils {
    /**
     * 检查应用packageName 是否存在
     *
     * @return true:存在 ，false:不存在
     */
    private fun checkPackInfo(packageName: String, context: Context): Boolean {
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = context.packageManager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return packageInfo != null
    }

    /**
     * 程序是否是前台
     */
    private fun isForeground(context: Context?): Boolean {
        if (context != null) {
            val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val processes = am.runningAppProcesses
            for (processInfo in processes) {
                if (processInfo.processName == context.packageName) {
                    if (processInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        return true
                    }
                }
            }
        }
        return false
    }

    /**
     * 判断B应用是否在后台运行并直接打开
     * 如果当次设备
     */
    private fun openPackage(context: Context, packageName: String): Boolean {
        val pkgContext = getPackageContext(context, packageName)
        val intent = getAppOpenIntentByPackageName(context, packageName)
        if (pkgContext != null && intent != null) {
            pkgContext.startActivity(intent)
            return true
        }
        return false
    }

    /**
     * 判断应用是否在运行中
     */
    private fun isRun(context: Context, packageName: String): Boolean {
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        //        List<ActivityManager.RunningTaskInfo> list1 = am.getRunningTasks(100);
//        List<ActivityManager.AppTask> list2 = am.getAppTasks();
//        List<ActivityManager.RunningAppProcessInfo> list3 = am.getRunningAppProcesses();
//        List<ActivityManager.RecentTaskInfo> list4 = am.getRecentTasks(100, RECENT_WITH_EXCLUDED);
        val list = am.getRunningTasks(100)
        var isAppRunning = false

        //100表示取的最大的任务数，info.topActivity表示当前正在运行的Activity，info.baseActivity表系统后台有此进程在运行
        for (info in list) {
            if (info.topActivity!!.packageName == packageName || info.baseActivity!!.packageName == packageName) {
                isAppRunning = true
                break
            }
        }
        return isAppRunning
    }

    /**
     * 获取程序B的上下文Context ，但是好像没什么效果
     */
    private fun getPackageContext(context: Context, packageName: String): Context? {
        var pkgContext: Context? = null
        if (context.packageName == packageName) {
            pkgContext = context
        } else {
            // 创建第三方应用的上下文环境
            try {
                pkgContext = context.createPackageContext(
                    packageName, Context.CONTEXT_IGNORE_SECURITY or Context.CONTEXT_INCLUDE_CODE
                )
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }
        }
        return pkgContext
    }

    /**
     * 拉起其他的App
     */
    fun pullApp(context: Context, pkgName: String): Boolean {
        //1. 判断程序B是否存在
        return if (checkPackInfo(pkgName, context)) {
            //2.判断程序A是否在前台运行
            val pkgContext = getPackageContext(context, pkgName)
            val isForeground = isForeground(context)
            isRun(context, pkgName)
            //3. 如果A正在前台运行，则说明程序B已经退出了
            if (isForeground) {
                //1. 启动方式1
                return openPackage(context, pkgName)
            } else {
                //已经在前台运行中，不用在拉起了
                true
            }
        } else {
            Toast.makeText(context, "需要拉起的软件还未安装,请先下载!", Toast.LENGTH_LONG).show()
            false
        }
    }

}